<template>
    <a-layout-content
            :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
    <a-button type="primary" @click="add">添加</a-button>
  <a-table :columns="columns"
           :row-key="record => record.id"
           :data-source="ebooks"
           :pagination="pagination"
           :loading="tableLoading"
           @change="handleTableChange"
            >
      <template #cover="{ text: cover }">
          <img v-if="cover" :src="cover" alt="avatar" />
      </template>
      <template v-slot:category="{ text, record }">
          <span>{{ getCategoryName(record.category1Id) }} / {{ getCategoryName(record.category2Id) }}</span>
      </template>
      <template v-slot:action="{text: record}" >
        <a-space>
            <router-link :to="'/admin/doc?ebookId=' + record.id">
                <a-button type="primary">
                    文档管理
                </a-button>
            </router-link>
          <a-button type="primary" :size="size" @click="edit(record)">修改</a-button>
          <a-button type="primary" danger @click="del(record.id)">删除</a-button>
        </a-space>
      </template>
  </a-table>
    </a-layout-content>
    <a-modal v-model:visible="modelVisible" title="修改电子书信息" @ok="handleOk">
        <a-form
                :model="ebook"
                v-bind="layout"
        >
            <a-form-item :name="['ebook', 'cover']" label="封面" :rules="[{ required: true }]">
                <a-input v-model:value="ebook.cover" />
            </a-form-item>
            <a-form-item :name="['ebook', 'name']" label="名称" :rules="[{ type: 'email' }]">
                <a-input v-model:value="ebook.name" />
            </a-form-item>
            <a-form-item label="分类">
                <a-cascader
                        v-model:value="categoryIds"
                        :field-names="{ label: 'name', value: 'id', children: 'children' }"
                        :options="categoryLevels"
                />
            </a-form-item>
            <a-form-item :name="['ebook', 'description']" label="描述">
                <a-input v-model:value="ebook.description" />
            </a-form-item>
            <a-form-item :name="['ebook', 'docCount']" label="文档数">
                <a-input v-model:value="ebook.docCount" />
            </a-form-item>
            <a-form-item :name="['ebook', 'viewCount']" label="阅读数">
                <a-input v-model:value="ebook.viewCount" />
            </a-form-item>
            <a-form-item :name="['ebook', 'voteCount']" label="点赞数">
                <a-input v-model:value="ebook.voteCount" />
            </a-form-item>
        </a-form>
    </a-modal>
    <a-modal v-model:visible="DeleteModelVisible" title="删除电子书" @ok="handleDeleteOk">
        <p>删除数据后不能恢复！</p>
    </a-modal>
</template>

<script lang="ts">
  import { SmileOutlined, DownOutlined } from '@ant-design/icons-vue';
  import { defineComponent, ref,onBeforeMount} from 'vue';
  import axios from 'axios';
  import { message } from 'ant-design-vue';
  import {Tool} from "@/util/tool";
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      slots: { customRender: 'cover' }
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '分类',
      slots: { customRender: 'category' }
    },
    {
      title: '描述',
      dataIndex: 'description',
    },
    {
      title: '文档数',
      dataIndex: 'docCount',
    },
    {
      title: '阅读数',
      dataIndex: 'viewCount',
    },
    {
      title: '点赞数',
      dataIndex: 'voteCount',
    },
    {
      title: '操作',
      key: 'action',
      slots: { customRender: 'action' }
    },
  ];
  //定义电子书的列表
  const ebooks = ref();
  //定义进度条的显示和隐藏
  const tableLoading = ref(false);
  //定义一个分页的对象
  const pagination =ref({
      current: 1,
      pageSize:3,
      total:0,
  });
   export default defineComponent({
     name: 'Ebook',
     components: {
       SmileOutlined,
       DownOutlined,
     },
    setup() {
      //进行异步请求获取后台数据
      const handleQuery = (params:any)=>{
          axios.get("/ebook/getPage",{
              params:{
                  current:params.current,
                  size:params.size,
              }
          }).then(function (response) {
              tableLoading.value = true;//显示进度条
              //接收返回的数据
              const result = response.data;
              console.log("后台返回的数据："+result);
              if(result.success){//请求成功
                  //取消进度条
                  tableLoading.value = false;
                  ebooks.value = response.data.content.records;//给响应式的变量赋值
                  //重置分页按钮
                  pagination.value.current = params.current;
                  pagination.value.pageSize = params.size;
                  pagination.value.total = result.content.total;
              }
          });
      };

        /**
         * 表格点击页码时触发
         */
        const handleTableChange = (pagination: any) => {
            console.log("看看自带的分页参数都有啥：" + pagination);
            //调用分页查询的方法
            handleQuery({
                size : pagination.pageSize,
                current : pagination.current,
            });
        };
        /**
         * 修改数据
         */
        const categoryIds = ref();
        //定义变量来控制弹窗的显示和隐藏
        const modelVisible = ref(false);
        const ebook = ref();
        const edit = (record:any) => {
            modelVisible.value = true;//显示弹窗
            ebook.value = record;//将对象的属性赋值给ebook对象
            console.log("====="+ebook.value);
            categoryIds.value = [ebook.value.category1Id, ebook.value.category2Id]
        };


        const handleOk = (e: MouseEvent) => {
            modelVisible.value = false;//隐藏弹窗
            ebook.value.category1Id = categoryIds.value[0];
            ebook.value.category2Id = categoryIds.value[1];
            axios.post("/ebook/save",ebook.value).then(function (response) {
                console.log("====="+ebook.value);
                //接收返回的数据
                const result = response.data;
                console.log("后台返回的数据："+result);
                if(result.success){//更新成功
                    message.info(result.message);
                    //重置分页按钮
                    // 重新加载列表
                    handleQuery({
                        page: pagination.value.current,
                        size: pagination.value.pageSize,
                    });
                }else{
                    message.error(result.message)
                }
            });
        };
        /**
         * 删除电子书
         * */
        const DeleteModelVisible = ref(false);
        let delId = -1;
        const del = (id:any) => {
            DeleteModelVisible.value = true;
            delId = id;
            console.log(id);
        };
        const handleDeleteOk = (e: MouseEvent) => {
            axios.post("/ebook/delete/"+delId).then(function (response) {
                //接收返回的数据
                const result = response.data;
                console.log("后台返回的数据："+result);
                if(result.success){//更新成功
                    message.info(result.message);
                    DeleteModelVisible.value = false;
                    //重新从数据库查询数据
                    handleQuery({
                        size : pagination.value.pageSize,
                        current : pagination.value.current,
                    });
                }else{
                    message.error(result.message)
                };
            });
        };
        /**
         * 添加电子书的方法
         *
         */
        const add = () => {
            //清空对象中的属性
            ebook.value = {};
            modelVisible.value = true;//显示弹窗
        };
        /**
         * 查找分类
         */
        const categoryLevels =  ref();
        let categorys: any;
        //进行异步请求获取后台数据
        const handleQueryCategory = ()=>{
            axios.get("/category/getAll").then(function (response) {
                //接收返回的数据
                const result = response.data;
                if(result.success){//请求成功
                    categorys = response.data.content;//给响应式的变量赋值
                    console.log("后台返回的数据："+categorys);
                    categoryLevels.value = Tool.array2Tree(categorys,0);//获取一级分类及其子分类
                    console.log("转换后的数据："+categoryLevels.value);
                    // 加载完分类后，再加载电子书，否则如果分类树加载很慢，则电子书渲染会报错
                    handleQuery({
                        page: 1,
                        size: pagination.value.pageSize,
                    });
                }
            });
        };
        const getCategoryName = (cid: number) => {
            // console.log(cid)
            let result = "";
            categorys.forEach((item: any) => {
                if (item.id === cid) {
                    // return item.name; // 注意，这里直接return不起作用
                    result = item.name;
                }
            });
            return result;
        };
        //页面加载完成后获取后台数据
        onBeforeMount(()=>{
            console.log("onBeforeMount");
            handleQueryCategory();
        });

      return {
        ebooks,
        columns,
        pagination,
        tableLoading,
        handleTableChange,
        edit,
        handleOk,
        modelVisible,
        ebook,
          del,
          add,
          handleDeleteOk,
          DeleteModelVisible,
          getCategoryName,
          categoryIds,
          categoryLevels,
      };
    }
  });
</script>
<style>
    img{
        width: 50px;
        height:50px;
    }
</style>
